package com.example.app.utils;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtils {

    @Value(value = "${JWT.typ}")
    private String typ;

    @Value(value = "${JWT.secret}")
    private String secret;

    @Value(value = "${JWT.alg}")
    private String alg;

    @Value(value = "${JWT.expire}")
    private long expire;

    public String createToken(Long userId) {
        JwtBuilder jwtBuilder = Jwts.builder();

        return jwtBuilder
                .setHeaderParam("typ", typ)
                .setHeaderParam("alg", alg)
                .claim("userId", userId)
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }

    public String createToken(Long userId, Long expire) {
        JwtBuilder jwtBuilder = Jwts.builder();

        return jwtBuilder
                .setHeaderParam("typ", typ)
                .setHeaderParam("alg", alg)
                .claim("userId", userId)
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }

    public Boolean checkToken(String token) {
        JwtParser jwtParser = Jwts.parser();
        if (token == null) {
            return false;
        }
        try {
            jwtParser.setSigningKey(secret).parse(token);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

}
